/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.gu.derp.beans.feeds;

import edu.gu.derp.model.Account;
import edu.gu.derp.model.Database;
import edu.gu.derp.model.Feed;
import edu.gu.derp.model.IController;
import java.net.URL;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

/**
 *
 * @author jensc
 */
@ManagedBean(name = "FeedsControllerBean")
@RequestScoped
public class FeedsControllerBean {   
    private final String ERROR_INCORRECT_FEED = "The feed could not be read.";
    
    @ManagedProperty(value = "#{FeedsBackingBean.feedUrl}")
    private String feedUrl;
    
    private IController controller = Database.getController();
    
    public void addFeed() {
        try {
            Account account = (Account) FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get("account");
            controller.addFeed(account, Feed.fromURL(new URL(feedUrl)));
        } catch (Exception e) {
            FacesContext context = FacesContext.getCurrentInstance();
            FacesMessage message = new FacesMessage();
            message.setDetail(ERROR_INCORRECT_FEED);
            message.setSummary(ERROR_INCORRECT_FEED);
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage("formAddRss:addRss", message);
        }
    }
    
    public void removeFeed(ActionEvent e) {
        Feed feed = (Feed) e.getComponent().getAttributes().get("data");
        Account account = (Account) FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get("account");
        controller.removeFeed(account, feed);
    }

    public String getFeedUrl() {
        return feedUrl;
    }

    public void setFeedUrl(String feedUrl) {
        this.feedUrl = feedUrl;
    }
}
